#include <stdio.h>
#include "login.h"

sqlite3 *db;
int sockfd;
int acceptfd;
int init_server(int port);
int main(int argc, char *argv[])
{
    FILE *fp;
    int port = 9966;
    if (argc > 1)
    {
        port = atoi(argv[1]);
    }

    // 初始化服务器
    sockfd = init_server(port);
    printf("init ok\n");
    // 打开数据库
    if (sqlite3_open("./gateWay.db", &db) != SQLITE_OK)
    {
        fprintf(stderr, "open err:%s", sqlite3_errmsg(db));
        return -1;
    }
    printf("database open ok\n");
    // 操作
    char *errmsg = NULL;
    // 创建表
    if (sqlite3_exec(db, "create table if not exists Login(account char primary key,password char);", NULL, NULL, &errmsg))
    {
        fprintf(stderr, "creat user err:%s\n", errmsg);
        return -1;
    }

    // 5.发送消息
    char buf[1024] = {0};
    // msg.acceptfd = sockfd;
    char account[64] = "";
    char password[64] = "";
    acceptfd = accept(sockfd, NULL, NULL);
    if (acceptfd < 0)
    {
        perror("accept err");
        return -1;
    }
    printf("accept ok\n");
    while (1)
    {
        memset(buf,0,sizeof(buf));
        
        int len=recv(acceptfd, buf, sizeof(buf), 0);
        if(len<=0)
        {
            printf("client close\n");
            close(acceptfd);
            acceptfd = accept(sockfd, NULL, NULL);
            if (acceptfd < 0)
            {
                perror("accept err");
                break;
            }
            printf("新客户端连接成功\n");
            continue;
        }        
        printf("buf:%s\n", buf);
        // 分割字符串
        char *token = strtok(buf, "/");
        if (token != NULL)
        {
            // 跳过第一个字段（注册标志）
            token = strtok(NULL, "/"); // 提取用户名
            if (token != NULL)
            {
                strncpy(account, token, sizeof(account) - 1);
                account[sizeof(account) - 1] = '\0'; // 确保字符串终止

                token = strtok(NULL, "/"); // 提取密码
                if (token != NULL)
                {
                    strncpy(password, token, sizeof(password) - 1);
                    password[sizeof(password) - 1] = '\0';
                }
                else
                {
                    printf("密码字段缺失\n");
                    password[0] = '\0'; // 清空密码
                }
            }
            else
            {
                printf("用户名字段缺失\n");
                account[0] = '\0'; // 清空用户名
            }
        }
        else
        {
            printf("无效的格式\n");
        }

        printf("用户名: %s\n", account);
        printf("密码: %s\n", password);
        if (buf[0] == '0') // 注册
        {
            Register(account, password);
        }
        else if (buf[0] == '1') // 登录
        {
            Login(account, password);
        }
    }
    return 0;
}

int init_server(int port) // 创建监听套接字
{

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        perror("socket failed");
        exit(2);
    }

    // 设置地址重用
    int opt = 1;
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    struct sockaddr_in local;
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = INADDR_ANY;

    if (bind(sock, (struct sockaddr *)&local, sizeof(local)) < 0)
    {
        perror("bind failed");
        exit(3);
    }

    if (listen(sock, 5) < 0)
    {
        perror("listen failed");
        exit(4);
    }

    return sock;
}
void Register(char *account, char *password)
{
    char buf[128] = "";
    char *errmsg = NULL;
    sprintf(buf, "insert into Login values(\"%s\",\"%s\")", account, password);
    printf("%s\n", buf);
    if (sqlite3_exec(db, buf, NULL, NULL, &errmsg) == 0)
    {
        printf("注册成功\n");
    }
    printf("errmsg==%s\n", errmsg);
}
void Login(char *account, char *password)
{
    char buf[128] = "";
    char **result = NULL;
    int row, column, ret;
    char *errmsg = NULL;

    sprintf(buf, "select password from Login where account='%s'", account);
    sqlite3_get_table(db, buf, &result, &row, &column, &errmsg);
    if (row > 0)
    {
        if (!strcmp(password, result[1]))
        {
            send(acceptfd, "1", 2, 0);
            printf("登陆成功\n");
        }
        else
        {
            send(acceptfd, "0", 2, 0);
            printf("登录失败\n");
        }
    }
    else
    {
        send(acceptfd, "0", 2, 0);
        printf("登录失败\n");
    }
}